package com.jy.api.controller;

import com.jy.api.dao.EmployeeDao;
import com.jy.api.dao.OrderDao;
import com.jy.api.domain.Employee;
import com.jy.api.domain.EmployeeKPI;
import com.jy.api.domain.EmployeeKPIItem;
import com.jy.api.domain.Order;
import com.jy.api.util.MyDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.time.OffsetDateTime;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * Created by hanxi on 2018/9/21.
 */
@RestController
public class EmployeeController {
    private OrderDao orderDao;
    private EmployeeDao employeeDao;

    private JdbcTemplate jdbc;

    @GetMapping(path = "/v1/employees/{username}/sales-kpi")
    public ResponseEntity getSalesKPI(@PathVariable String username, @RequestParam String storeId, @RequestParam int year, @RequestParam int month) {
        Employee employee = employeeDao.findByStoreIdAndUsernameAndEnabled(storeId, username, true);
        String s = year + "-" + month;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        Date start = MyDateUtils.getMinMonthDate(s);
        Date end = MyDateUtils.getMaxMonthDate(s);
        EmployeeKPI kpi = new EmployeeKPI();
        BeanPropertyRowMapper itemMapper = new BeanPropertyRowMapper<>(EmployeeKPIItem.class);
        itemMapper.setPrimitivesDefaultedForNullValue(true);
        List<EmployeeKPIItem> items = jdbc.query("SELECT SUM(oi.`quantity`) AS qty , SUM(oi.`deal_price`) AS amount , p.`parent_type_name` AS typeName FROM `order_item` oi LEFT JOIN `product` p on oi.`product_id`= p.`id` WHERE `order_id` IN(SELECT `id` FROM `order` o WHERE `store_id`=?  AND `creator_id`=?  AND o.`payment_time`> ?   AND o.`payment_time`<= ?  AND `enabled`= 1 AND o.`status` IN('UNFINISHED', 'FINISHED') AND `enabled`= 1)  AND oi.`enabled`= 1 GROUP BY p.`parent_type_name`  ORDER BY amount DESC "
                , itemMapper, storeId, username, simpleDateFormat.format(start), simpleDateFormat.format(end));
        double a = 0.0;
        int b = 0;
        for (EmployeeKPIItem kpiItem : items) {
            a += kpiItem.getAmount();
            b += kpiItem.getQty();
            if (null == kpiItem.getTypeName() || kpiItem.getTypeName().equals("")) {
                kpiItem.setTypeName("会员充值");
            }
        }
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        nf.setGroupingUsed(false);
        kpi.setTarget(employee.getTarget());
        kpi.setAmount(Double.valueOf(nf.format(a)));
        kpi.setItems(items);
        kpi.setQty(b);
        return ResponseEntity.ok(kpi);
    }


    @GetMapping(path = "/v1/employees/{username}/orders")
    public ResponseEntity getOrders(@PathVariable String username, @RequestParam String storeId, @RequestParam Date fromDate, @PageableDefault(size = 10, sort = {"paymentTime"}, direction = Sort.Direction.DESC) Pageable page) {
        OffsetDateTime fromTime = OffsetDateTime.parse(fromDate + "T00:00:00+08:00");
        Page<Order> orders = orderDao.findListByStoreIdAndCreatorIdAndPaymentTimeGreaterThanEqualAndEnabled(storeId, username, new Date(fromTime.toInstant().toEpochMilli()), true, page);
        return ResponseEntity.ok(orders);
    }


    @Autowired
    public void setOrderDao(OrderDao orderDao) {
        this.orderDao = orderDao;
    }

    @Autowired
    public void setEmployeeDao(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }

    @Autowired
    public void setJdbc(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }
}
